package com.stadium.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.stadium.common.exception.RRException;
import com.stadium.common.utils.SqlMapper;
import com.stadium.common.utils.UserUtils;
import com.stadium.dto.*;
import com.stadium.entity.GameEvent;
import com.stadium.entity.SysAdminUser;
import com.stadium.entity.SysUser;
import com.stadium.mapper.*;
import com.stadium.service.GameEventSV;
import com.stadium.service.REventTeamSV;
import com.stadium.service.TeamLogSV;
import com.stadium.service.UserMessageSV;
import com.stadium.vo.GameEventVo;
import com.stadium.vo.REventTeamVo;
import com.stadium.vo.TeamLogVo;
import com.stadium.vo.UserMessageVo;
import com.stadium.vo.searchVo.GameEventSearchVo;
import com.stadium.vo.searchVo.GameScheduleSearchVo;
import com.stadium.vo.searchVo.GameTeamSearchVo;
import com.stadium.vo.searchVo.RTeamUserSearchVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@Slf4j
public class GameEventSVI implements GameEventSV {
    @Autowired
    private GameEventMP mapper;
    @Autowired
    private SqlMapper sqlMapper;
    @Autowired
    private REventTeamSV rEventTeamSV;
    @Autowired
    private RTeamUserMP rTeamUserMP;
    @Autowired
    private REventTeamMP rEventTeamMP;
    @Autowired
    private GameScheduleMP gameScheduleMP;
    @Autowired
    private TeamLogSV teamLogSV;
    @Autowired
    private GameTeamMP gameTeamMP;
    @Autowired
    private UserMessageSV userMessageSV;
    @Autowired
    private SysUserMP sysUserMP;

    @Override
    public List<GameEvent> queryBySQL(String sql, Map<String, Object> map) {
        return sqlMapper.selectList(sql, map, GameEvent.class);
    }

    @Override
    public void save(GameEventVo gameEventVo) {
        GameEvent gameEvent = new GameEvent();
        BeanUtils.copyProperties(gameEventVo, gameEvent);
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        gameEvent.setCreateUser(UserUtils.getUserId());
        gameEvent.setUpdateUser(UserUtils.getUserId());
        gameEvent.setId(id);
        mapper.save(gameEvent);
        if (gameEventVo.getUserId() != null) {
            SysAdminUser sysAdminUser = new SysAdminUser();
            String adminId = UUID.randomUUID().toString().replaceAll("-", "");
            sysAdminUser.setId(adminId);
            sysAdminUser.setAuditStatus("1");
            sysAdminUser.setArea(gameEventVo.getAddress());
            sysAdminUser.setContact(gameEventVo.getSponsor());
            sysAdminUser.setPhoneNum(gameEvent.getPhoneNum());
            sysAdminUser.setRegisterTime(new Date());
            sysAdminUser.setCreateUser(UserUtils.getUserId());
            sysAdminUser.setUpdateUser(UserUtils.getUserId());
            SysUser sysUser = new SysUser();
            sysUser.setId(gameEventVo.getUserId());
            sysUser.setIsAdmin("1");
            sysUser.setUpdateUser(UserUtils.getUserId());
            sysUserMP.update(sysUser);
        }
    }

    @Override
    public void update(GameEventVo gameEventVo) {
        GameEventDto gameEventDto = mapper.get(gameEventVo.getId());
        GameEvent gameEvent = new GameEvent();
        BeanUtils.copyProperties(gameEventVo, gameEvent);
        gameEvent.setUpdateUser(UserUtils.getUserId());
        mapper.update(gameEvent);
        if (gameEventVo.getUserId() != null) {
            SysUser sysUser = new SysUser();
            sysUser.setId(gameEventVo.getUserId());
            sysUser.setIsAdmin("1");
            sysUser.setUpdateUser(UserUtils.getUserId());
            sysUserMP.update(sysUser);
            sysUser.setId(gameEventDto.getUserId());
            sysUser.setIsAdmin("0");
            sysUser.setUpdateUser(UserUtils.getUserId());
            sysUserMP.update(sysUser);
        }
    }

    @Override
    public void saveBatch(List<GameEvent> list) {
        mapper.saveBatch(list);
    }

    @Override
    public void delete(String id) {
        mapper.delete(id);
    }

    @Override
    public void deleteBatch(String[] ids) {
        mapper.deleteBatch(ids);
    }

    @Override
    public List<GameEventDto> query(GameEventSearchVo searchVo) {
        List<GameEventDto> gameEventDtoList =  mapper.query(searchVo);
        for (GameEventDto gameEventDto: gameEventDtoList) {
            if(gameEventDto.getRegistrationEndtime().getTime() > new Date().getTime()){
                gameEventDto.setStatus("报名中");
            }
            if(belongCalendar(new Date(),gameEventDto.getRegistrationEndtime(),gameEventDto.getCompetitionEndtime())){
                gameEventDto.setStatus("进行中");
            }

            if(gameEventDto.getCompetitionEndtime().getTime() < new Date().getTime()){
                gameEventDto.setStatus("已结束");
            }
            if (searchVo.getIsNeedteam().equals("1") || searchVo.getIsNeedschedule().equals("1")) {
                if (searchVo.getIsNeedteam().equals("1")) {
                    List<TeamListDto> teamListDtoList = mapper.getTeamsByEventId(gameEventDto.getId());
                    gameEventDto.setTeamList(teamListDtoList);
                }
                if (searchVo.getIsNeedschedule().equals("1")) {
                    GameScheduleSearchVo gameScheduleSearchVo = new GameScheduleSearchVo();
                    gameScheduleSearchVo.setEventId(gameEventDto.getId());
                    List<GameScheduleDto> gameScheduleDtoList = gameScheduleMP.query(gameScheduleSearchVo);
                    gameEventDto.setScheduleList(gameScheduleDtoList);
                }
            }
        }
        return gameEventDtoList;
    }

    /**
     * 判断时间是否在时间段内
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public GameEventDto get(String id) {
        GameEventDto gameEventDto =  mapper.get(id);
        List<TeamListDto> list = rEventTeamSV.queryTeamByEventId(gameEventDto.getId());
        gameEventDto.setTeamList(list);
        return gameEventDto;
    }

    @Override
    public int getCount(GameEventSearchVo searchVo) {
        return mapper.getCount(searchVo);
    }

    @Override
    public List<GameTeamDto> auditTeam(GameTeamSearchVo vo) {
        List<GameTeamDto> gameTeamDtoList =  mapper.auditTeam(vo);
        for (GameTeamDto gameTeamDto:gameTeamDtoList) {
            RTeamUserSearchVo rTeamUserSearchVo = new RTeamUserSearchVo();
            rTeamUserSearchVo.setTeamId(gameTeamDto.getId());
            int total = rTeamUserMP.getCount(rTeamUserSearchVo);
            gameTeamDto.setPalyerNum(total);
        }
        return gameTeamDtoList;
    }

    @Override
    public int auditTeamCount(GameTeamSearchVo vo) {
        return mapper.auditTeamCount(vo);
    }

    @Override
    public void audit(String rid, String status) {
        REventTeamDto rEventTeamDto = rEventTeamSV.get(rid);
        if (rEventTeamDto == null) {
            log.warn("球队审批不存在{}",rid);
            throw new RRException("申请不存在");
        }
        REventTeamVo rEventTeamVo = new REventTeamVo();
        rEventTeamVo.setId(rid);
        rEventTeamVo.setAuditStatus(status);
        rEventTeamSV.update(rEventTeamVo);
        GameEventDto gameEventDto = mapper.get(rEventTeamDto.getEventId());
        if (gameEventDto == null) {
            log.warn("赛事不存在或已被删除，赛事id{}",rEventTeamDto.getTeamId());
            throw new RRException("赛事不存在或已被删除");
        }
        if("1".equals(status)){
            GameTeamDto gameTeamDto = gameTeamMP.get(rEventTeamDto.getTeamId());
            TeamLogVo teamLogVo = new TeamLogVo();
            teamLogVo.setContent(gameEventDto.getName());
            teamLogVo.setArea(gameEventDto.getAddress());
            teamLogVo.setTeamId(rEventTeamDto.getTeamId());
            teamLogSV.save(teamLogVo);

            UserMessageVo userMessage=  new UserMessageVo();
            userMessage.setUserId(gameTeamDto.getUserId());
            userMessage.setContent("恭喜您，报名成功，您得球队“"+gameTeamDto.getName()+"”已成功加入“"+gameEventDto.getName()+"”赛事，请留意比赛时间，准时参加");
            userMessageSV.save(userMessage);
        }
        if("0".equals(status)){
            GameTeamDto gameTeamDto = gameTeamMP.get(rEventTeamDto.getTeamId());
            TeamLogVo teamLogVo = new TeamLogVo();
            teamLogVo.setContent(gameEventDto.getName());
            teamLogVo.setArea(gameEventDto.getAddress());
            teamLogVo.setTeamId(rEventTeamDto.getTeamId());
            teamLogSV.save(teamLogVo);

            UserMessageVo userMessage=  new UserMessageVo();
            userMessage.setUserId(gameTeamDto.getUserId());
            userMessage.setContent("恭喜您，报名成功，您得球队“"+gameTeamDto.getName()+"”已被拒绝加入“"+gameEventDto.getName()+"”赛事，请知悉");
            userMessageSV.save(userMessage);
        }

    }

    @Override
    public List<TeamListDto> getTeamsByEventId(String eventId) {
        return mapper.getTeamsByEventId(eventId);
    }

    @Override
    public List<EventAndScheduleDto> queryByPlayerUserId(String userId) {
        String[] teamIds = rTeamUserMP.getTeamIdsByUserId(userId);
        if (teamIds == null || teamIds.length <= 0) {
            return new ArrayList<>(0);
        }
        List<EventAndScheduleDto> list = rEventTeamMP.getEventByTeamIds(teamIds);
        Long time = new Date().getTime();
        if (list != null) {
            List<EventAndScheduleDto> list2 = list.stream().filter((eventAndScheduleDto) -> (eventAndScheduleDto.getRegistrationEndtime().getTime() < time)).collect(Collectors.toList());
            list2.stream().forEach((EventAndScheduleDto eventAndScheduleDto) ->{
                if (eventAndScheduleDto.getRegistrationStarttime().getTime() > time && eventAndScheduleDto.getRegistrationEndtime().getTime() < time) {
                    eventAndScheduleDto.setStatus("报名中");
                } else if(eventAndScheduleDto.getRegistrationEndtime().getTime() > time && eventAndScheduleDto.getCompetitionEndtime().getTime() < time){
                    eventAndScheduleDto.setStatus("进行中");
                }else if(eventAndScheduleDto.getCompetitionEndtime().getTime() < time ){
                    eventAndScheduleDto.setStatus("已结束");
                }
                GameScheduleSearchVo gameScheduleSearchVo = new GameScheduleSearchVo();
                gameScheduleSearchVo.setEventId(eventAndScheduleDto.getId());
                gameScheduleSearchVo.setTeamId(eventAndScheduleDto.getTeamId());
                List<GameScheduleDto> gameScheduleDtoList = gameScheduleMP.query(gameScheduleSearchVo);
                if (gameScheduleDtoList != null) {
                    gameScheduleDtoList.stream().forEach(gameScheduleDto -> {
                        if (gameScheduleDto.getCompetitionEndtime().getTime() < time) {
                            gameScheduleDto.setCompetitionStauts("0");
                        } else if (gameScheduleDto.getCompetitionStarttime().getTime() < time && gameScheduleDto.getCompetitionEndtime().getTime() > time) {
                            gameScheduleDto.setCompetitionStauts("1");
                        }else if (gameScheduleDto.getCompetitionEndtime().getTime() < time) {
                            gameScheduleDto.setCompetitionStauts("2");
                        }
                    });
                    eventAndScheduleDto.setGameScheduleDtoList(gameScheduleDtoList);
                }else {
                    eventAndScheduleDto.setGameScheduleDtoList(new ArrayList<>(0));
                }
            });
            return list2;
        }

        return null;
    }

}
